<?php

namespace App\Admin\Controllers;

use App\Models\Crouse;
use App\Models\Crousesheet;
use App\Models\Notice;
use App\Models\Squad;
use App\Models\Class_type;
use App\Models\Class_section_group;
use App\Models\Campus;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Auth\Database\Role;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use DB;
use App\Admin\Extensions\ExcelExpoter;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class SquadController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.squad'));
            $content->description(trans('admin.list'));

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(trans('admin.squad'));
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.squad'));
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Squad::class, function (Grid $grid) {
            $user = Admin::user()->id;
            //找出当前登陆用户管理的班段ID，并取出该班段下的所有班级ID集合
            $user_section_ids = Class_section_group::where('pid','0')->whereRaw('FIND_IN_SET('.$user.',`charge`)')->pluck('id')->toArray();
            $user_squad_ids1 = Squad::whereIn('section',$user_section_ids)->pluck('id')->toArray();
            //dd($user_squad_ids1);
            //找出当前登陆用户管理的分组ID，，并取出该分组下的所有班级ID集合
            $user_group_ids = Class_section_group::where('pid','>','0')->whereRaw('FIND_IN_SET('.$user.',`charge`)')->pluck('id')->toArray();
            //dd($user_group_ids);
            $user_squad_ids2 = Squad::whereIn('group',$user_group_ids)->pluck('id')->toArray();
            //dd($user_squad_ids2);

            //找出当前登陆用户作为班主任管理的班级ID
            $user_squad_ids3 = Squad::where('class_teacher',$user)->pluck('id')->toArray();

            //把当前登陆用户有权看的班级ID拼合起来，需要去重？
            $user_squad_ids = array_keys(array_flip($user_squad_ids1)+array_flip($user_squad_ids2)+array_flip($user_squad_ids3));
            //dd($user_squad_ids);
            if (!Admin::user()->isRole('supper_admin')) {
                $grid->model()->whereIn('id',$user_squad_ids);
            }
            $grid->id(trans('admin.ID'))->sortable();
            $grid->type(trans('admin.type'))->display(function($type){
                if ($this->type==0) {
                    return 'N/A';
                }else{
                    return Class_type::find($this->type)->name;
                }
            })->sortable();
            $grid->no(trans('admin.no'))->sortable();
            $grid->section(trans('admin.section'))->display(function($section){
                if ($this->section==0) {
                    return 'N/A';
                }else{
                    return Class_section_group::find($this->section)->name;
                }
            })->sortable();
            $grid->group(trans('admin.group'))->display(function($group){
                if ($this->group==0) {
                    return 'N/A';
                }else{
                    return Class_section_group::where('id',$this->group)->value('name');
                }
            })->sortable();

            
            $grid->campus(trans('admin.campus'))->display(function($campus){
                if ($this->campus==0) {
                    return 'N/A';
                }else{
                    return Campus::find($this->campus)->name;
                }
            })->sortable();
            //$grid->class_teacher(trans('admin.class_teacher'));
            $grid->class_teacher(trans('admin.class_teacher'))->display(function($class_teacher){
                if ($this->class_teacher==0) {
                    return 'N/A';
                }else{
                    return Admin::user()->where('id',$this->class_teacher)->value('username');
                }
            })->sortable();
            $grid->batch('开班批次');

            $grid->column('人数')->display(function(){
                $num = DB::table('students')->where('squad_id',$this->id)->where('status','1')->count();
                return '<a href="my_squad/'.$this->id.'" style="text-decoration:underline">'.$num.'</a>';
            });

            $grid->study_jindu('教学进度');

            $grid->actions(function ($actions) {
                $actions->disableView();
                if (!Admin::user()->isRole('supper_admin')) {
                    $actions->disableDelete();
                }
            });

            //禁用导出按钮
            //$grid->disableExport();
            $filename="班级列表";
            $grid->exporter(new ExcelExpoter($grid,$filename));
            
            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });
            $grid->filter(function ($filter) {
                $filter->column(1/2, function ($filter) {
                    $filter->disableIdFilter();
                    $filter->equal('type', trans('admin.type'))->select(Class_type::all()->pluck('name', 'id'));
                    $filter->equal('section', trans('admin.section'))->select(Class_section_group::where('pid','=','0')->get()->pluck('name', 'id'));
                    $filter->equal('campus', trans('admin.campus'))->select(Campus::all()->pluck('name', 'id'));
                    $filter->equal('start_year', trans('admin.start_year'))->year();
                    $filter->equal('batch',trans('admin.batch'));
                });
                $filter->column(1/2, function ($filter) {
                    $filter->equal('no',trans('admin.no'));
                    $filter->equal('group', trans('admin.group'))->select(Class_section_group::where('pid','!=','0')->get()->pluck('name', 'id'));
                    // $filter->equal('class_teacher', trans('admin.class_teacher'))->select(Admin::user()->where('type','=','1')->get()->pluck('name', 'id'));
                    $filter->equal('start_season', trans('admin.start_season'))->radio([
                        ''   => trans('admin.all'),
                        '1'  => trans('admin.spring'),
                        '2'  => trans('admin.autumn'),
                    ]);
                });
                
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Squad::class, function (Form $form) {
            $data = array();
            $form->display('id', 'ID');

            $form->select('type', trans('admin.type'))->options(Class_type::all()->pluck('name', 'id'))->rules('required')->addElementLabelClass('must-input');
            $form->select('section', trans('admin.section'))->options(Class_section_group::where('pid','=','0')->get()->pluck('name', 'id'))->load('group', '/api/get_group')->rules('required')->addElementLabelClass('must-input');
            $form->select('group',trans('admin.group'))->options(function ($id){
                    return Class_section_group::options($id);
            }); 
            //$form->select('group',trans('admin.group'))->options(array(0 =>'请选择分组')); 
            $form->number('no', trans('admin.no'))->min(1)->max(999)->rules('required')->addElementLabelClass('must-input');
            $form->select('campus', trans('admin.campus'))->options(Campus::all()->pluck('name', 'id'))->rules('required')->addElementLabelClass('must-input');
            
            $form->select('class_teacher', trans('admin.class_teacher'))->options(Admin::user()->pluck('username', 'id'))->rules('required')->addElementLabelClass('must-input');
            $form->date('start_year', trans('admin.start_year'))->format('YYYY')->rules('required')->addElementLabelClass('must-input');
            $form->radio('start_season', trans('admin.start_season'))->options(['1' => trans('admin.spring'), '2'=> trans('admin.autumn')])->default('1');
            $form->date('batch', trans('admin.batch'))->rules('required')->format('YYYY-MM')->addElementLabelClass('must-input');
            $form->hasMany('squad_crouse', '配置课程', function (Form\NestedForm $form1) {
                $form1->select('crouse_id','选择')->options(function(){
                    return Crouse::all()->pluck('name','id');
                });
            });

            $form->saving(function (Form $form) use (&$data){
                $data = $form->input('squad_crouse');
            });

            //保存后回调
            $form->saved(function (Form $form) use (&$data) {
                $a = $data;
                $crouses = DB::table('squad_crouses')->where('squad_id',$form->model()->id)->get();
                $arr = array();
                foreach($crouses as $v){
                    $arr[] = $v->crouse_id;
                }
                if(count($a) != count($arr)){
                    DB::table('set_crousesheets')->where('squads_id',$form->model()->id)->delete();
                }else{
                    $i=0;
                    foreach($a as $v){
                        if($v['crouse_id'] != $arr[$i]){
                            DB::table('set_crousesheets')->where('squads_id',$form->model()->id)->delete();
                            break;
                        }
                        $i++;
                    }
                }
                Crousesheet::where('squads_id',$form->model()->id)->where('status','=',1)->update(['tutor_id'=>$form->model()->class_teacher]);
                Notice::where('status','1')->where('squad_id',$form->model()->id)->update(['tutor_id'=>$form->model()->class_teacher]);
                $type_name = Class_type::find($form->type)->name;
                $section_name = Class_section_group::find($form->section)->name;
                $group_name = Class_section_group::find($form->group)->name;
                $no = $form->no;
                $squad_name = $type_name.''.$no;
                $squad_full_name = $type_name.''.$no.'('.$section_name.'-'.$group_name.')';
                //$max_id = Squad::max('id');
                $squad = Squad::find($form->model()->id);
                $squad->name = $squad_name;
                $squad->full_name = $squad_full_name;
                $squad->save();
            });
            

            //去掉添加/编辑表单的重置按钮
            $form->disableReset();

            // $form->display('created_at', 'Created At');
            // $form->display('updated_at', 'Updated At');
        });
    }
}
